import SockJS from "sockjs-client";
import Stomp from "stompjs";
export const sockjsMixins = {
  data() {
    return {
      timer: null,
      subscription: null,
    };
  },
  activated() {
    this.createStompClient();
  },
  deactivated() {
    this.disconnect();
    clearInterval(this.timer);
  },
  beforeDestroy: function () {
    // 页面离开时断开连接,清除定时器
    this.disconnect();
    clearInterval(this.timer);
  },
  methods: {
    createStompClient() {
      const self = this;
      // 建立连接对象
      this.socket = new SockJS("http://localhost:9000/ws", null, {
        timeout: 15000,
      }); //连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(this.socket);
      // 定义客户端的认证信息,按需求配置
      // 向服务器发起websocket连接
      this.stompClient.connect(
        () => {
          //连接成功，发送订阅
          self.clientOnConnectHandle();
        },
        (err) => {
          // 连接发生错误时的处理函数
          console.log(err);
        },
        (val) => {
          // 订阅连接断开事件
          self.clientOnDisconnectHandle();
        }
      );
    },
    // 断开连接
    disconnect() {
      if (this.stompClient != null) {
        this.stompClient.disconnect();
        this.unsubscribe();
        this.stompClient = null;
      }
    },

    // 订阅连接断开事件
    clientOnDisconnectHandle() {
      const that = this;
      that.closeStompClient(); // 先关闭之前的socket连接
      this.timer = window.setTimeout(() => {
        that.createStompClient(); // 再重新创建一个新的socket连接
        window.clearTimeout(that.reload);
      }, 2000);
    },

    // 清除订阅
    unsubscribe() {
      if (this.subscription) {
        this.subscription.unsubscribe();
        this.subscription = null;
      }
    },

    // 关闭之前的socket连接
    closeStompClient() {
      if (this.stompClient) {
        this.unsubscribe();
        this.stompClient = null; // 清空stompClient对象
      }
    },
  },
};